import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.LocalStorage 2.15
import QtQuick.Layouts 1.15
import QtQuick.Dialogs 1.3  

ApplicationWindow {
    width: 800
    height: 600
    visible: true
    title: qsTr("File example")


    FileDialog {
        id: fileDialog
        title: "选择文件"
        onAccepted: {
            fileList.model.append({
                fileName: fileDialog.fileUrl.toString().split('/').pop(),
                fileSize: 1024,  // 这里可以添加实际的文件大小获取逻辑
                fileType: "text/plain"  // 这里可以添加实际的文件类型检测逻辑
            })
        }
    }


    // 主布局
    RowLayout {
        anchors.fill: parent
        anchors.margins: 10
        spacing: 20

        // 左侧面板
        ColumnLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: 10

            // 文件操作区
            GroupBox {
                title: "文件操作"
                Layout.fillWidth: true
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 10

                    TextArea {
                        id: textArea
                        Layout.fillWidth: true
                        height: 150
                        text: fileIO.text
                    }

                    Button {
                        text: "读取文件"
                        Layout.alignment: Qt.AlignHCenter
                        onClicked: fileIO.read()
                    }

                    Text {
                        text: fileIO.error ? fileIO.errorString : "读取成功"
                        color: fileIO.error ? "red" : "green"
                    }
                }
            }

            // 数据库操作区
            GroupBox {
                title: "数据库操作"
                Layout.fillWidth: true
                Layout.fillHeight: true
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 10

                    RowLayout {
                        Layout.fillWidth: true
                        TextField {
                            id: keyInput
                            Layout.fillWidth: true
                            placeholderText: "输入键"
                        }
                        TextField {
                            id: valueInput
                            Layout.fillWidth: true
                            placeholderText: "输入值"
                        }
                    }

                    RowLayout {
                        Layout.fillWidth: true
                        Button {
                            text: "保存"
                            Layout.fillWidth: true
                            onClicked: {
                                if (keyInput.text && valueInput.text) {
                                    setSetting(keyInput.text, valueInput.text)
                                    resultText.text = "已保存: " + keyInput.text + " = " + valueInput.text
                                }
                            }
                        }
                        Button {
                            text: "读取"
                            Layout.fillWidth: true
                            onClicked: {
                                if (keyInput.text) {
                                    var value = getSetting(keyInput.text, "未找到")
                                    valueInput.text = value
                                    resultText.text = "读取结果: " + keyInput.text + " = " + value
                                }
                            }
                        }
                    }

                    ScrollView {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        Text {
                            id: resultText
                            width: parent.width
                            wrapMode: Text.WordWrap
                            text: "操作结果将显示在这里"
                        }
                    }
                }
            }
        }

        // 右侧面板 - 文件列表
        GroupBox {
            title: "文件列表"
            Layout.fillWidth: true
            Layout.fillHeight: true
            ColumnLayout {
                anchors.fill: parent
                spacing: 10

                Button {
                    text: "选择文件"
                    Layout.fillWidth: true
                    onClicked: fileDialog.open()
                }

                ListView {
                    id: fileList
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    model: ListModel{}
                    delegate: Column {
                        width: parent.width
                        spacing: 5
                        Text { text: "文件名: " + model.fileName }
                        Text { text: "文件大小: " + model.fileSize + " bytes" }
                        Text { text: "文件类型: " + model.fileType }
                        Rectangle {
                            width: parent.width
                            height: 1
                            color: "lightgray"
                        }
                    }
                }

                Button {
                    id: bt1
                    text: "添加文件"
                    Layout.fillWidth: true
                    onClicked: {
                        fileList.model.append({
                            fileName: "example.txt",
                            fileSize: 1024,
                            fileType: "text/plain"
                        })
                    }
                }
            }
        }

        GroupBox {
            title: "数据流处理"
            Layout.fillWidth: true
            Layout.fillHeight: true

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 20

                spacing: 15

                TextField {
                    id: urlInput
                    width: parent.width
                    placeholderText: "输入URL"
                    text: "https://jsonplaceholder.typicode.com/posts/1"
                }

                Button {
                    text: "发送 GET 请求"
                    onClicked: {
                        sendGetRequest(urlInput.text)
                    }
                }

                Button {
                    text: "发送 POST 请求"
                    onClicked: {
                        sendPostRequest(urlInput.text)

                    }
                }
                
                ScrollView {
                    width: parent.width
                    height: 200

                    TextArea {
                        id: responseText
                        readOnly: true
                        placeholderText: "响应内容将显示在这里..."
                    }
                }

                Text {
                    id: statusText
                    color: "blue"
                }
            }


        }
    }

    // 隐藏的文件输入元素
    Rectangle {
        id: fileInput
        visible: false
    }

    // 文件IO组件
    FileIO {
        id: fileIO
    }
    function sendGetRequest(url) {
        var xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    responseText.text = xhr.responseText
                    statusText.text = "请求成功"
                    statusText.color = "green"
                } else {
                    statusText.text = "请求失败: " + xhr.status
                    statusText.color = "red"
                }
            }
        }
        xhr.open("GET", url)
        xhr.send()
    }

    function sendPostRequest(url, data) {
        var xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function() {
            
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    responseText.text = xhr.responseText
                    statusText.text = "请求成功"
                    statusText.color = "green"
                } else {
                    statusText.text = "请求失败: " + xhr.status
                    statusText.color = "red"

                }
            }
        }

        xhr.open("POST", url)
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.send(data)
    }

    Component.onCompleted: initDatabase()

    // 数据库相关函数
    function initDatabase() {
        var db = LocalStorage.openDatabaseSync("MyDate", "1.0", "本地存储示例", 1000000)
        db.transaction(function(tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS Test (id unique, name)')
        })
    }

    function setSetting(key, value) {
        var db = LocalStorage.openDatabaseSync("MyDate", "1.0", "本地存储示例", 1000000)
        db.transaction(function(tx) {
            tx.executeSql('INSERT OR REPLACE INTO Test (id, name) VALUES (?, ?)', [key, value])
        })
    }

    function getSetting(key, defaultValue) {
        var db = LocalStorage.openDatabaseSync("MyDate", "1.0", "本地存储示例", 1000000)
        var value = defaultValue
        db.transaction(function(tx) {
            var result = tx.executeSql('SELECT name FROM Test WHERE id=?', [key])
            if (result.rows.length > 0) {
                value = result.rows.item(0).name
            }
        })
        return value
    }
}
